<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--组织数据-->
      <el-col :span="device=='pc'?5:7" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入组织名称"
            clearable
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container head-tree">
          <el-tree
            :data="deptOptions"
            :props="{ label: 'deptName', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :current-node-key="currentKey"
            ref="deptTreeRef"
            node-key="deptCode"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--日历数据-->
      <el-col :span="device=='pc'?19:17" :xs="24">
        <el-calendar v-model="nowDate">
          <template #date-cell="{ data }">
            <div
              :class="['day-content', { 'pass-time': isDisabled(data) }]"
              @click.stop="showDetail(data)"
            >
              <span class="day">{{ data.day.split("-")[2] }}</span>
              <span
                v-if="statusData[data.day] == 'OFF'"
                class="status off-work"
                size="mini"
                >休</span
              >
              <span
                v-else-if="statusData[data.day] == 'NOT'"
                class="status off-work"
                size="mini"
                >班/休</span
              >
              <span
                v-else-if="statusData[data.day] == 'ON'"
                class="status"
                size="mini"
                >班</span
              >
            </div>
          </template>
        </el-calendar>
      </el-col>
    </el-row>
    <weekdaySetDialog
      v-model="weekdayDialog"
      :weekData="weekData"
      :baseData="baseData"
      :baseDataCode="baseDataCode"
      :baseDataId="baseDataId"
      :weekdayItem="weekdayItem"
      @submit-success="submitSuccess"
    />
    <weekdayDetail
      v-model="showWeekdayDetail"
      :weekData="weekData"
      :baseData="baseData"
      :baseDataCode="baseDataCode"
      :baseDataId="baseDataId"
      :weekdayItem="weekdayItem"
      :configDisabled="configDisabled"
      @config-click="handleStatusChange"
    />
  </div>
</template>
<script setup name="WorkdaySetting">
import { ClickOutside as vClickOutside } from "element-plus";

import { listDept } from "@/api/system/dept";
import {
  addWorkday,
  updateWorkday,
  listWorkday,
  delWorkday,
  getWorkday,
} from "@/api/base/plan/shiftMgt/workdaySetting";
import weekdaySetDialog from "./weekdaySetDialog";
import weekdayDetail from "./weekdayDetail";
import { getFactoryTree, depeIdSelectList } from "@/api/system/dept";
import { listLineProduceStatus } from "@/api/base/plan/shiftMgt/userChange";
import { unref } from "vue";

const { proxy } = getCurrentInstance();
const weekStr = ["日", "一", "二", "三", "四", "五", "六"];

var currentArrCode = ref([]);
var currentArrName = ref([]);
var currentArrId = ref([]);
const deptName = ref("");
const currentKey = ref("");
const deptOptions = ref(undefined);
const nowDate = ref(new Date());
const statusData = ref({});
const workItem = ref({});
const currentDate = ref({});
const weekdayItem = ref({});
const weekData = ref({});
const baseData = ref({});
const baseDataCode = ref({});
const baseDataId = ref({});
const newDateTime = new Date().setHours(0, 0, 0, 0);
const buttonRef = ref();
const weekdayDialog = ref(false);
const showWeekdayDetail = ref(false);
const configDisabled = ref(false);
const popoverRef = ref("popoverRef");
const device = ref(localStorage.getItem("device"));
const data = reactive({
  form: {},
  queryParams: {
    factory: "",
    dept: "",
    workshopCode: "",
    sectionCode: "",
    productLine: "",
    yearStr: new Date().getFullYear(),
    monthStr:
      new Date().getMonth() + 1 > 9
        ? new Date().getMonth() + 1
        : "0" + (new Date().getMonth() + 1),
  },
});

const { queryParams, form, rules } = toRefs(data);

const onClickOutside = (date) => {
  buttonRef.value = `cell${date}`;
  unref(popoverRef).popperRef?.delayHide?.();
};
/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.deptName.indexOf(value) !== -1;
};
/** 根据名称筛选组织树 */
watch(deptName, (val) => {
  proxy.$refs["deptTreeRef"].filter(val);
});
/**  */
watch(nowDate, (val) => {
  // 中国标准时间
  let date1 = val;
  // 年
  let y = date1.getFullYear();
  // 月
  let m = date1.getMonth() + 1;
  m = m < 10 ? "0" + m : m;
  // 日
  let d = date1.getDate();
  d = d < 10 ? "0" + d : d;
  // 时
  let h = date1.getHours();
  h = h < 10 ? "0" + h : h;
  // 分
  let M = date1.getMinutes();
  M = M < 10 ? "0" + M : M;
  // 秒
  let s = date1.getSeconds();
  s = s < 10 ? "0" + s : s;
  let dateTime = y + "-" + m + "-" + d + " " + h + ":" + M + ":" + s;
  queryParams.value.yearStr = y;
  queryParams.value.monthStr = m;
  getList();
});

function getLastDay(year, month) {
  //返回月份最后一天，不写参数默认返回本月最后一天
  var date = new Date(),
    date2,
    day;
  if (year === undefined) year = date.getFullYear(); //获取今年年份
  if (month === undefined) month = date.getMonth() + 1; //获取本月月份
  date2 = new Date(year, month, 0); //在JS中,如果使用new Date函数,可以使用传参数形式获取某一月的最后一天,并且自动判断润平年和大小月;
  day = date2.getDate(); //最后一天
  console.log(year, month, day);
  range.value = [year + "-" + month + "01", year + "-" + month + day];
}

// 切换状态
function handleStatusChange(date, data) {
  showWeekdayDetail.value = false;
  weekdayDialog.value = true;
}

function getFactorys() {
  getFactoryTree().then((res) => {
    deptOptions.value = res.data;
    // response.data.map((el) => {
    //   el.label = el.deptName;
    // });
    // deptOptions.value = proxy.handleTree(response.data, "deptId");
    currentKey.value = deptOptions.value[0].children[0].deptCode;
    currentArrName.value = [
      deptOptions.value[0].deptName,
      deptOptions.value[0].children[0].deptName,
    ];
    currentArrCode = [
      deptOptions.value[0].deptCode,
      deptOptions.value[0].children[0].deptCode,
    ];
    currentArrId = [
      deptOptions.value[0].deptId,
      deptOptions.value[0].children[0].deptId,
    ];
    nextTick(() => {
      proxy.$refs["deptTreeRef"].setCurrentKey(
        deptOptions.value[0].children[0].deptCode
      );
      getList(
        deptOptions.value[0].deptCode,
        deptOptions.value[0].children[0].deptCode
      );
    });
  });
}

function submitSuccess(value) {
  weekdayDialog.value = false;
  if (value) {
    getList();
  }
}
/** 查询组织下拉树结构 */
// function getDeptTree() {
//   listDept().then((response) => {
//     response.data.map((el) => {
//       el.label = el.deptName;
//     });
//     deptOptions.value = proxy.handleTree(response.data, "deptId");
//     currentKey.value = deptOptions.value[0].children[0].deptCode;
//     currentArrName.value = [
//       deptOptions.value[0].deptName,
//       deptOptions.value[0].children[0].deptName,
//     ];
//     currentArrCode = [
//       deptOptions.value[0].deptCode,
//       deptOptions.value[0].children[0].deptCode,
//     ];
//     currentArrId = [
//       deptOptions.value[0].deptId,
//       deptOptions.value[0].children[0].deptId,
//     ];
//     nextTick(() => {
//       proxy.$refs["deptTreeRef"].setCurrentKey(
//         deptOptions.value[0].children[0].deptCode
//       );
//       getList(deptOptions.value[0].children[0].deptCode);
//     });
//   });
// }

function isDisabled(date) {
  let _day = date.day;
  return new Date(_day).getTime() < newDateTime;
}

function isExistRest(value, index, ar) {
  if (value?.produceStatus == "ON") {
    return true;
  } else {
    return false;
  }
}
/** 节点单击事件 */
function handleNodeClick(data, node, self) {
  currentArrCode = findParent(deptOptions.value, data.deptCode, "deptCode")
    .reverse()
    .concat(data.deptCode);
  currentArrId = findParent(deptOptions.value, data.deptCode, "deptId")
    .reverse()
    .concat(data.deptId);
  currentArrName.value = findParent(
    deptOptions.value,
    data.deptCode,
    "deptName"
  )
    .reverse()
    .concat(data.deptName);
  queryParams.value.factory = currentArrCode[0] || "";
  queryParams.value.workshopCode = currentArrCode[1] || "";
  queryParams.value.productLine = currentArrCode[2] || "";
  queryParams.value.sectionCode = currentArrCode[3] || "";
  getList();
}
function findParent(dataSource, nodeId, type) {
  const parentIds = []; // 用于存储所有父节点ID的数组 // 定义一个递归函数，用于遍历整棵树并查找子节点的所有父节点
  function traverse(node, nodeId) {
    if (node.deptCode === nodeId) {
      // 如果当前节点的ID等于子节点的ID，则表示已经找到了子节点，可以开始向上查找父节点
      return true; // 返回true表示已经找到了子节点
    }
    if (node.children) {
      // 如果当前节点有子节点，则继续遍历子节点
      for (const childNode of node.children) {
        if (traverse(childNode, nodeId)) {
          // 如果在子节点中找到了子节点的父节点，则将当前节点的ID添加到父节点ID数组中，并返回true表示已经找到了子节点
          parentIds.push(node[type]);
          return true;
        }
      }
    }
    return false; // 如果当前节点不是子节点的父节点，则返回false
  } // 从根节点开始遍历整棵树，并调用递归函数查找子节点的所有父节点
  for (const node of dataSource) {
    if (traverse(node, nodeId)) {
      // 如果在当前节点的子树中找到了子节点的父节点，则直接退出循环
      break;
    }
  }
  return parentIds; // 返回所有父节点ID的数组
}

function showDetail(data) {
  // type: 'prev-month' | 'current-month' | 'next-month',
  // isSelected: boolean,
  // day: string, date: Date
  if (!queryParams.value.factory) {
    proxy.$modal.msgError("请选择工厂");
    return;
  }
  packageData(data);
  configDisabled.value = isDisabled(data);
  showWeekdayDetail.value = true;
}
//组装数据
function packageData(data) {
  const days = data.day.split("-");
  const week = data.date.getDay();
  const {
    factory,
    workshopCode,
    productLine,
    factoryName,
    workshopName,
    lineName,
    sectionCode,
  } = queryParams.value;
  weekData.value = {
    year: days[0],
    month: days[1],
    day: days[2],
    week: `星期${weekStr[week]}`,
  };
  baseData.value = currentArrName.value;
  baseDataCode.value = currentArrCode;
  baseDataId.value = currentArrId;
  weekdayItem.value = workItem.value[data.day];
}

function getList(a, b) {
  weekdayDialog.value = false;
  if (a) {
    queryParams.value.factory = a;
    queryParams.value.workshopCode = b;
  }
  const { factory, workshopCode, productLine, sectionCode, yearStr, monthStr } =
    queryParams.value;
  const params = {
    factory,
    workshopCode,
    productLine,
    sectionCode,
    yearStr,
    monthStr,
  };
  listWorkday(params)
    .then((res) => {
      if (res.code == 200) {
        const dataList = res.data;
        let classesDutyList = [];
        for (let key in dataList) {
          let day = key > 9 ? key : "0" + key;
          let dataKey =
            queryParams.value.yearStr +
            "-" +
            queryParams.value.monthStr +
            "-" +
            day +
            "";
          if (dataList[key]) {
            classesDutyList = dataList[key]?.classesDutyList;
            if (classesDutyList?.length) {
              //工厂，车间，产线，工艺段四个层级数据
              let lineList = [];
              classesDutyList.forEach((ele, index) => {
                if (ele?.workshopDutyInfoList?.length) {
                  ele.workshopDutyInfoList.forEach((item) => {
                    if (item?.lineDutyInfoList?.length) {
                      item.lineDutyInfoList.forEach((tar) => {
                        if (tar?.sectionDutyInfoDtoList?.length) {
                          tar.sectionDutyInfoDtoList.forEach((ts) => {
                            lineList.push({
                              produceStatus: ts.produceStatus,
                            });
                            currentDate.value[dataKey] = lineList;
                          });
                        } else {
                          lineList.push({
                            produceStatus: "ON",
                          });
                          currentDate.value[dataKey] = lineList;
                        }
                      });
                    } else {
                      lineList.push({
                        produceStatus: "ON",
                      });
                      currentDate.value[dataKey] = lineList;
                    }
                  });
                } else {
                  lineList.push({
                    produceStatus: "ON",
                  });
                  currentDate.value[dataKey] = lineList;
                }
              });
              console.log(currentDate);
              for (let idx in currentDate.value) {
                if (currentDate.value[idx].every(isExistRest)) {
                  //所有产线都是工作日
                  statusData.value[idx] = "ON";
                } else {
                  if (!currentDate.value[idx].some(isExistRest)) {
                    //都是休息日
                    statusData.value[idx] = "OFF";
                  } else {
                    statusData.value[idx] = "NOT";
                  }
                }
              }
            }
          } else {
            //没有配置休息和工作日
            nextTick(() => {
              statusData.value[dataKey] = "ON";
            });
          }
          workItem.value[dataKey] = dataList[key];
        }
      }
    })
    .catch(() => {});
}

getFactorys();
</script>
<style lang="scss" scoped>
.head-tree {
  height: 500px;
  overflow: auto;
}
:deep(.el-calendar-table) {
  thead th::before {
    content: "星期";
  }
  td.is-selected {
    background: none;
  }
  td.is-today {
    color: inherit;
  }
  .el-calendar-day {
    padding: 0;
    &:hover {
      background: none;
      cursor: pointer;
    }
  }
}
.day-content {
  width: 100%;
  height: 100%;
  padding: 16px;
  .day {
    display: inline-block;
    vertical-align: middle;
    width: 50px;
    height: 34px;
    line-height: 34px;
    text-align: center;
  }
  .status {
    display: inline-block;
    vertical-align: middle;
    width: 36px;
    height: 26px;
    line-height: 26px;
    text-align: center;
    border-radius: 6px;
    font-size: 14px;
    background: #88c446;
    color: #ffffff;
    cursor: pointer;
    &.off-work {
      background: #f56c6c;
    }
  }
  &.pass-time {
    background-color: #f5f5f5;
    .status {
      opacity: 0.75;
    }
  }
}

:deep(.el-calendar-table):not(.is-range) td.prev,
:deep(.el-calendar-table):not(.is-range) td.next {
  cursor: not-allowed;
  pointer-events: none;
}
.prev > .el-calendar-day > div {
  display: none;
}
.next > .el-calendar-day > div {
  display: none;
}
</style>
